package com.cs.auth.domain.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.cs.auth.common.bos.AuthCaptchaBO;
import com.cs.auth.common.entity.ErrorCode;
import com.cs.auth.common.exception.BusinessException;
import com.cs.auth.domain.service.AuthCaptchaDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.cs.auth.domain.redis.RedisUtil;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthCaptchaDomainServiceImpl implements AuthCaptchaDomainService {

    @Resource
    private RedisUtil redisUtil;

    private static final String CAPTCHA_KEY = "captcha:";

    /**
     * 获取验证码
     * @return
     */
    @Override
    public AuthCaptchaBO getCaptcha() {
        // 生成验证码uuid
        String uuid = UUID.randomUUID().toString();
        // 生成验证码
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(300, 100, 4, 4);
        // 获取验证码内容
        String code = captcha.getCode();
        // 获取验证码图片Base64
        String image = captcha.getImageBase64();
        // 将验证码存入Redis
        redisUtil.setNx(CAPTCHA_KEY + uuid, code, 5L, TimeUnit.MINUTES);
        // 返回验证码
        AuthCaptchaBO authCaptchaBO = new AuthCaptchaBO();
        authCaptchaBO.setUuid(uuid);
        authCaptchaBO.setImg(image);
        log.info("生成验证码：{}", code);
        return authCaptchaBO;
    }

    @Override
    public Boolean checkCaptcha(String code, String uuid) {
        boolean flag = redisUtil.exist(CAPTCHA_KEY + uuid);
        if (!flag){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"验证码不存在");
        }
        // 获取redis中的答案
        String answer = redisUtil.get(CAPTCHA_KEY + uuid);
        if (answer == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"验证码不存在");
        }
        // 删除验证码
        redisUtil.del(CAPTCHA_KEY + uuid);
        // 转换大小写
        code = code.toUpperCase();
        answer = answer.toUpperCase();
        // 比较验证码
        if (!answer.equals(code)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码错误");
        }
        return true;
    }
}
